package com.atsmart.app.activity;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.MessageAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.MessageInfo;
import com.atsmart.app.model.MessageListInfo;
import com.atsmart.app.model.MessagePageInfo;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.sql.MessageSqlHelper;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;

public class MessageListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, OnClickListener,
		LoadingAdapter.OnLoadingRowShowingHandler {
	private static final String TAG = MessageListActivity.class.getName();
	public static final String Ser_Key = "choosen";
	private ListView listView;
	private MessageListInfo datasource;
	private MessageAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private Button btnWrite;
	private Button refresh;
	private MessageSqlHelper msql = null;
	private boolean asyntaskIsFinished = false;
	private SimpleDateFormat sdf;
	private NumberSqlHelper nsql = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_list_layout);
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		refresh = (Button) findViewById(R.id.btn_refresh);
		btnWrite = (Button) findViewById(R.id.btn_history);
		btnWrite.setBackgroundResource(R.drawable.btn_write_selector);
		btnWrite.setPadding(5, 0, 5, 0);
		btnWrite.setVisibility(View.VISIBLE);
		msql = new MessageSqlHelper();
		msql.open(BizApp.getInstance().getSqlHelper());
//		totalRow = msql.getCount();
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		nsql.deleteAttributeByType(4);
		NumberResponseInfo at = new NumberResponseInfo();
		at.setLastTime(Calendar.getInstance().getTimeInMillis());
		at.setType(4);
		nsql.addNumberInfo(at);
		refresh.setOnClickListener(this);
		btnWrite.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listview);
	}


	@Override
	protected void onResume() {
		super.onResume();
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
		nsql.deleteAttributeByType(4);
		NumberResponseInfo at = new NumberResponseInfo();
		at.setLastTime(Calendar.getInstance().getTimeInMillis());
		at.setType(4);
		nsql.addNumberInfo(at);
		// if (BizApp.getInstance().isNetworkAvailable()
		// || BizApp.getInstance().isWiFiActive()) {
		// login();
		// }
		 
		if(BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive()){
			showLoading();
			asyntaskIsFinished = false;
			getData();
		}else{
			Toast.makeText(this, "无可用网络！", Toast.LENGTH_SHORT).show();
		}
//		}else{
//			int count = msql.getCount();
//			Log.i(TAG, "count: = " + count);
//			datasource = msql.getMessageInfo(0,count);
//			
//			asyntaskIsFinished = true;
//			finishedLoad(TAG);
//		}

	}

	public class Phone implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("phone")
		public String phone;
	}

	private int isPage = 0;
	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<MessageListInfo>() {

			@Override
			protected MessageListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				CommonBody body = new CommonBody();
				body.setCommand(6);
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(BizApp.getInstance().getString(
						R.string.app_version));
				MessagePageInfo pageInfo = new MessagePageInfo();
				pageInfo.begin = pageIndex * pageSize + isPage;
//				pageInfo.end = (pageIndex + 1) * pageSize - 1;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				Calendar calendar = Calendar.getInstance();

				if (StringUtil.isEmptyOrNull(PrefsUtils.getLastMsgDate())) {
					calendar.add(Calendar.MONTH, -6);
					pageInfo.dateBegin = sdf.format(calendar.getTime());
				} else {
					pageInfo.dateBegin = PrefsUtils.getLastMsgDate();
				}
				pageInfo.dateEnd = sdf.format(new Date());
				pageInfo.type = 3;
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.getMsgURL(), gson.toJson(body),
						gson.toJson(pageInfo), MessageListInfo.class);
			}

			@Override
			protected void runWithResult(MessageListInfo result)
					throws Exception {
				if (result != null) {
					result.Sequence();
					datasource = result;
					bindData();
				}
				nsql.deleteAttributeByType(1);
				NumberResponseInfo at = new NumberResponseInfo();
				at.setLastTime(Calendar.getInstance().getTimeInMillis());
				at.setType(1);
				nsql.addNumberInfo(at);
				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(MessageListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;

				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void getDataByUrl2() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<MessageListInfo>() {

			@Override
			protected MessageListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				CommonBody body = new CommonBody();
				body.setCommand(6);
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(BizApp.getInstance().getString(
						R.string.app_version));
				MessagePageInfo pageInfo = new MessagePageInfo();
				pageInfo.begin = pageIndex * pageSize + isPage;
//				pageInfo.end = (pageIndex + 1) * pageSize - 1;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				Calendar calendar = Calendar.getInstance();

				if (StringUtil.isEmptyOrNull(PrefsUtils.getLastMsgDate())) {
					calendar.add(Calendar.MONTH, -6);
					pageInfo.dateBegin = sdf.format(calendar.getTime());
				} else {
					pageInfo.dateBegin = PrefsUtils.getLastMsgDate();
				}
				pageInfo.dateEnd = sdf.format(new Date());
				pageInfo.type = 3;
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.getMsgURL(), gson.toJson(body),
						gson.toJson(pageInfo), MessageListInfo.class);
			}

			@Override
			protected void runWithResult(MessageListInfo result)
					throws Exception {
				if (result != null) {
					result.Sequence();
					datasource = result;
					bindData();
				}
				nsql.deleteAttributeByType(1);
				NumberResponseInfo at = new NumberResponseInfo();
				at.setLastTime(Calendar.getInstance().getTimeInMillis());
				at.setType(1);
				nsql.addNumberInfo(at);
				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(MessageListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;

				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}

	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new MessageAdapter(datasource);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View v, int arg2,
						long arg3) {
					// TODO Auto-generated method stub
					// 分组点击动画
					MessageInfo choosen = (MessageInfo) adapter.getItem(arg2);
					if (choosen != null) {
						Intent newone = new Intent(MessageListActivity.this,
								MessageDetailActivity.class);
						Bundle mBundle = new Bundle();
						mBundle.putSerializable(Ser_Key, choosen);
						newone.putExtras(mBundle);

						startActivity(newone);
					}

				}
			});
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		totalRow = datasource.getRows();
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData();
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			DialogUtil.getExitAppDialog(this).show();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			if (BizApp.getInstance().isNetworkAvailable()
					|| BizApp.getInstance().isWiFiActive()) {
				showLoading();
				asyntaskIsFinished = false;
				getData();

			}
		} else if (v.getId() == R.id.btn_history) {
			IntentUtil.redirectToNext(MessageListActivity.this,
					SendMsgActivity.class);
		}

	}
}
